//
//  ATQueyTrackViewController.m
//  ATGaode_demo
//
//  Created by Chengquan Ye on 2019/3/5.
//  Copyright © 2019年 Chengquan Ye. All rights reserved.
//

#import "ATQueyTrackViewController.h"
#import <AMapTrackKit/AMapTrackKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "ATStepNumberManager.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define iPhone4S [UIScreen mainScreen].bounds.size.height == 480
#define iPhone5S [UIScreen mainScreen].bounds.size.height == 568
#define iPhone6S [UIScreen mainScreen].bounds.size.height == 667
#define iPhonePlus [UIScreen mainScreen].bounds.size.height == 736
#define iPad ([UIScreen mainScreen].bounds.size.height > 736 && [UIScreen mainScreen].bounds.size.height != 812)
#define iPhoneX ([UIScreen mainScreen].bounds.size.height == 812 && [UIScreen mainScreen].bounds.size.width == 375)
#define iPhoneXR [UIScreen mainScreen].bounds.size.height == 896
#define iPhoneXS_MAX [UIScreen mainScreen].bounds.size.height == 896
#define iPhoneX_series (iPhoneX || iPhoneXR || iPhoneXS_MAX)

#define NavHeight (iPhoneX_series ? 88 : 64)
#define TabBarHeight (iPhoneX_series ? 83 : 49)
#define SafeBottomHeight (iPhoneX_series ? 34 : 0)


static NSString * const key = @"7cd0c6e32639e7ff175727a4f7e17ecc";
static NSString * const serviceName = @"轨迹测试服务";
static NSString * const clientName = @"轨迹测试终端";

static NSString * const sid = @"26335"; // 服务id
static NSString * const tid = @"28257710"; // 终端id

@interface ATQueyTrackViewController () <AMapTrackManagerDelegate, MAMapViewDelegate, ATStepNumberManagerDelegate>

/** <#name#> */
@property (nonatomic, strong) AMapTrackManager *trackManager;

/** <#name#> */
@property (nonatomic, strong) ATStepNumberManager *stepNumberManager;

/** 高德地图view */
@property (nonatomic, strong) MAMapView *mapView;
/** 步数 */
@property (nonatomic, weak) UILabel *stepNumLbl;
/** 里程，计步器计算 */
@property (nonatomic, weak) UILabel *distanceLbl;
/** 里程，高德计算 */
@property (nonatomic, weak) UILabel *distanceOtherLbl;

///第几页数据，默认1
@property (nonatomic, assign) NSUInteger pageIndex;

///每页数据量，默认20，有效值范围[1, 1000)
@property (nonatomic, assign) NSUInteger pageSize;


/** 轨迹点数据数组 */
@property (nonatomic, strong) NSMutableArray<AMapTrackPoint *> *trackPointArray;

@end

@implementation ATQueyTrackViewController

- (NSMutableArray<AMapTrackPoint *> *)trackPointArray
{
    if (!_trackPointArray) {
        _trackPointArray = [NSMutableArray array];
    }
    return _trackPointArray;
}

- (ATStepNumberManager *)stepNumberManager
{
    if (!_stepNumberManager) {
        _stepNumberManager = [ATStepNumberManager manager];
        _stepNumberManager.delegate = self;
    }
    return _stepNumberManager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"轨迹记录";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
    
    [self initializeTrackManager];
    
//    [self queryHistoryAndDistanceTracks];
    if (self.startDate && self.endDate) {
        [self.stepNumberManager stepNumberWithStartDate:self.startDate endDate:self.endDate];
    }
    
    [self queryTracks];
    
    [self queryDistance];
}

#pragma mark - 初始化轨迹管理
- (void)initializeTrackManager
{
    AMapTrackManagerOptions *option = [[AMapTrackManagerOptions alloc] init];
    option.serviceID = sid; //Service ID 需要根据需要进行修改
    
    //初始化AMapTrackManager
    self.trackManager = [[AMapTrackManager alloc] initWithOptions:option];
    self.trackManager.delegate = self;
    
    // a.配置定位属性
    [self.trackManager setAllowsBackgroundLocationUpdates:YES];
    [self.trackManager setPausesLocationUpdatesAutomatically:NO];
    
    self.pageIndex = 1;
    self.pageSize = 2;
}

/** 查询历史轨迹和里程 */
- (void)queryHistoryAndDistanceTracks
{
    //查询历史轨迹和距离
    AMapTrackQueryTrackHistoryAndDistanceRequest *request = [[AMapTrackQueryTrackHistoryAndDistanceRequest alloc] init];
    request.serviceID = self.trackManager.serviceID;
    request.terminalID = tid; //self.terminalID;
    request.startTime = [self.startDate timeIntervalSince1970] * 1000;// ([[NSDate date] timeIntervalSince1970] - 12*60*60) * 1000;
    request.endTime = [self.endDate timeIntervalSince1970] * 1000; // [[NSDate date] timeIntervalSince1970] * 1000; //
    //    request.correctionMode = @"denoise=1,mapmatch=1,threshold=20"; //@"denoise=1,mapmatch=1,threshold=0,mode=driving"; 抽稀去噪，轨迹绑路纠偏，定位精度过滤, 交通方式，猎鹰将根据不同交通工具选择不同的纠偏策略，目前支持驾车示例
    request.recoupMode = AMapTrackRecoupModeNone;
    request.pageSize = self.pageSize; // 每页返回点的数量，最大不超过1000
    request.pageIndex = self.pageIndex;
    
    [self.trackManager AMapTrackQueryTrackHistoryAndDistance:request];
}

- (void)queryDistance
{
//    NSLog(@"serviceID:%@, terminalID:%@, trackID:%@, startDate:%@, endDate:%@", self.trackManager.serviceID, self.terminalID, self.trackID, self.startDate, self.endDate);
    AMapTrackQueryTrackDistanceRequest *request = [[AMapTrackQueryTrackDistanceRequest alloc] init];
    request.serviceID = self.trackManager.serviceID; // @"26335"; //
    request.terminalID = self.terminalID; // @"28257710"; //
    request.trackID = self.trackID; // @"680"; //
    request.startTime = [self.startDate timeIntervalSince1970] * 1000;
    request.endTime = [self.endDate timeIntervalSince1970] * 1000;
    
    [self.trackManager AMapTrackQueryTrackDistance:request];
}

- (void)queryTracks
{
    NSLog(@"serviceID:%@, terminalID:%@, trackID:%@, startDate:%@, endDate:%@", self.trackManager.serviceID, self.terminalID, self.trackID, self.startDate, self.endDate);
    AMapTrackQueryTrackInfoRequest *request = [[AMapTrackQueryTrackInfoRequest alloc] init];
    request.serviceID = self.trackManager.serviceID; // @"26335"; //
    request.terminalID = self.terminalID; // @"28257710"; //
    request.trackID = self.trackID; // @"680"; //
    request.startTime = [self.startDate timeIntervalSince1970] * 1000;
    request.endTime = [self.endDate timeIntervalSince1970] * 1000;
    request.pageSize = self.pageSize; // 每页返回点的数量，最大不超过1000
    request.pageIndex = self.pageIndex;
//    request.correctionMode = @"denoise=1,mapmatch=1,threshold=0,mode=driving";
    
    [self.trackManager AMapTrackQueryTrackInfo:request];
}

- (void)setupUI
{
    /*创建地图并添加到父view上*/
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, NavHeight, SCREEN_WIDTH, SCREEN_HEIGHT - NavHeight - SafeBottomHeight)];
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    
    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    //    self.mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    //    self.mapView.distanceFilter = 5; // kCLDistanceFilterNone
    
    //    self.mapView.pausesLocationUpdatesAutomatically = NO;
    
    // 不显示罗盘
    self.mapView.showsCompass = NO;
    
    // 不显示比例尺
    self.mapView.showsScale = NO;
    
    //是否自定义用户位置精度圈
    self.mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    MACircle *circle = [MACircle circleWithCenterCoordinate:self.mapView.userLocation.coordinate radius:0];
    [self.mapView addOverlay:circle];
    
    [self.mapView setZoomLevel:20];
//    [self.mapView setMaxZoomLevel:19];
    
    // 修改地图样式
    NSString *path = [NSString stringWithFormat:@"%@/style.data", [NSBundle mainBundle].bundlePath];
    NSData *styleData = [NSData dataWithContentsOfFile:path];
    MAMapCustomStyleOptions *styleOption = [[MAMapCustomStyleOptions alloc] init];
    styleOption.styleData = styleData;
    [self.mapView setCustomMapStyleOptions:styleOption];
    [self.mapView setCustomMapStyleEnabled:YES];
    
    UILabel *stepNumLbl = [[UILabel alloc] init];
    stepNumLbl.frame = CGRectMake(10, SCREEN_HEIGHT - 10 * 2 - 30 * 3, 150, 30);
    //    stepNumLbl.textAlignment = NSTextAlignmentRight;
    stepNumLbl.textColor = [UIColor whiteColor];
    stepNumLbl.backgroundColor = [UIColor blackColor];
    stepNumLbl.text = @"步数: 0米";
    [self.view addSubview:stepNumLbl];
    self.stepNumLbl = stepNumLbl;
    
    UILabel *distanceLbl = [[UILabel alloc] init];
    distanceLbl.frame = CGRectMake(10, SCREEN_HEIGHT - 10 - 30 * 2, 150, 30);
    //    distanceLbl.textAlignment = NSTextAlignmentRight;
    distanceLbl.textColor = [UIColor redColor];
    distanceLbl.textColor = [UIColor whiteColor];
    distanceLbl.backgroundColor = [UIColor blackColor];
    distanceLbl.text = @"计步: 0米";
    [self.view addSubview:distanceLbl];
    self.distanceLbl = distanceLbl;
    
    UILabel *distanceOtherLbl = [[UILabel alloc] init];
    distanceOtherLbl.frame = CGRectMake(10, SCREEN_HEIGHT - 30, 150, 30);
    //    distanceOtherLbl.textAlignment = NSTextAlignmentRight;
    distanceOtherLbl.textColor = [UIColor redColor];
    distanceOtherLbl.textColor = [UIColor whiteColor];
    distanceOtherLbl.backgroundColor = [UIColor blackColor];
    distanceOtherLbl.text = @"高德: 0米";
    [self.view addSubview:distanceOtherLbl];
    self.distanceOtherLbl = distanceOtherLbl;
}

#pragma mark - AMapTrackManagerDelegate

- (void)didFailWithError:(NSError *)error associatedRequest:(id)request {
    NSLog(@"didFailWithError:%@; --- associatedRequest:%@;", error, request);
}

#pragma mark - 查询历史轨迹和里程
- (void)onQueryTrackHistoryAndDistanceDone:(AMapTrackQueryTrackHistoryAndDistanceRequest *)request response:(AMapTrackQueryTrackHistoryAndDistanceResponse *)response {
    NSLog(@"onQueryTrackHistoryAndDistanceDone 轨迹点: %zd---里程: %zd", response.points.count, response.distance);
    
    if ([[response points] count] > 0) {
//        [self.mapView removeOverlays:[self.mapView overlays]];
        
        [self showPolylineWithTrackPoints:[response points]];
        [self.mapView showOverlays:self.mapView.overlays animated:NO];
        
        if (response.points.count == self.pageSize) {
            self.pageIndex++;
            
            [self queryTracks];
        }
    } else {
        
    }
    
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"轨迹历史和里程" message:response.formattedDescription delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
//    [alertView show];
}

#pragma mark - 查询历史轨迹点
- (void)onQueryTrackInfoDone:(AMapTrackQueryTrackInfoRequest *)request response:(AMapTrackQueryTrackInfoResponse *)response {
    NSLog(@"onQueryTrackInfoDone%@", response.formattedDescription);
    
    [self.mapView removeOverlays:[self.mapView overlays]];
    
    AMapTrackBasicTrack *track  = response.tracks.lastObject;
    
    if (track.points.count > 0) {
        [self.trackPointArray addObjectsFromArray:[track points]];
        if (track.points.count == self.pageSize) { // 刚好等于分页的大小，重新请求
            self.pageIndex++;
            [self queryTracks];
        } else { // 获取的轨迹数小于分页大小，说明没有轨迹点了
            [self showPolylineWithTrackPoints:self.trackPointArray];
            [self.mapView showOverlays:self.mapView.overlays animated:NO];
        }
    } else { // 没有轨迹了
        if (self.trackPointArray.count > 0) {
            [self showPolylineWithTrackPoints:self.trackPointArray];
            [self.mapView showOverlays:self.mapView.overlays animated:NO];
        }
    }
   
    
    
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"轨迹历史" message:response.formattedDescription delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
//    [alertView show];
}

#pragma mark - 查询轨迹里程
- (void)onQueryTrackDistanceDone:(AMapTrackQueryTrackDistanceRequest *)request response:(AMapTrackQueryTrackDistanceResponse *)response
{
    NSLog(@"onQueryTrackDistanceDone %@", response.formattedDescription);
    self.distanceOtherLbl.text = [NSString stringWithFormat:@"高德: %zd米", response.distance];
}

- (void)onQueryLastPointDone:(AMapTrackQueryLastPointRequest *)request response:(AMapTrackQueryLastPointResponse *)response
{
    //查询成功
    NSLog(@"onQueryLastPointDone%@", response.formattedDescription);
}

#pragma mark - 画轨迹
- (void)showPolylineWithTrackPoints:(NSArray<AMapTrackPoint *> *)points {
    int pointCount = (int)[points count];
    
    CLLocationCoordinate2D *allCoordinates = (CLLocationCoordinate2D *)malloc(pointCount * sizeof(CLLocationCoordinate2D));
    for (int i = 0; i < pointCount; i++) {
        allCoordinates[i].latitude = [[points objectAtIndex:i] coordinate].latitude;
        allCoordinates[i].longitude = [[points objectAtIndex:i] coordinate].longitude;
    }
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:allCoordinates count:pointCount];
    [self.mapView addOverlay:polyline];
    
    if (allCoordinates) {
        free(allCoordinates);
        allCoordinates = NULL;
    }
}

#pragma mark - MapView Delegate
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        
        MAPolylineRenderer * polylineRenderer = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
        polylineRenderer.lineWidth = 5.f;
        polylineRenderer.strokeColor = [UIColor greenColor];
        
        return polylineRenderer;
    }
    
    return nil;
}

#pragma mark - ATStepNumberManagerDelegate
- (void)stepNumber:(NSDictionary *)dict
{
    self.stepNumLbl.text = [NSString stringWithFormat:@"步数: %@步", dict[@"numberOfSteps"]];
    self.distanceLbl.text = [NSString stringWithFormat:@"计步: %zd米", [dict[@"distance"] integerValue]];
}

- (void)dealloc {
    [self.trackManager stopService];
    self.trackManager.delegate = nil;
    self.trackManager = nil;
    
    [self.mapView removeFromSuperview];
    self.mapView.delegate = nil;
    self.mapView = nil;
}

@end
